package inv.stask.logic;

import inv.stask.beans.Task;

import java.io.File;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

public class ArchiverUtil extends WriterUtil {
	public static final SimpleDateFormat sdf_yyyyMMdd	= new SimpleDateFormat("yyyyMMdd"); 
	
	protected MyProperties prop		= new MyProperties();
	protected String filename		= prop.getArchiveDir() + File.separator + "arh-";
	protected String filenameLock	= prop.getArchiveDir() + File.separator + "archive.ser.lock";

	@Override
	protected String getFilename() {
		int copy = 0;
		String f1 = filename + sdf_yyyyMMdd.format(new Date()) + ".ser";
		while(new File(f1).exists()){
			copy ++;
			f1 = filename + sdf_yyyyMMdd.format(new Date()) + "-" + copy + ".ser";
		}
		
		return f1;
	}

	@Override
	protected String getLockFilename() {
		return filenameLock;
	}
	
	public String[] listArchiveFiles() {
		File dir	= new File(prop.getArchiveDir());
		return dir.list(new FilenameFilter(){
			String patternText	= "arh-[\\d]{8}(.*)+\\.ser";
			Pattern pattern = Pattern.compile(patternText);
			public boolean accept(File dir, String name) {
				if(pattern.matcher(name).matches())
					return true;
				
				System.out.println("does not match: " + name);
				return false;
			}
		});
	}
	
	private void prepareIds(List<Task> tasks){
		int maxId	= 0;
		for(Task task: tasks){
			if(task.getId() != null)
				if(task.getId() > maxId)
					maxId = task.getId();
		}
		
		for(Task task: tasks){
			if(task.getId() == null)
				task.setId(++maxId);
		}
	}
	
	public void write(List<Task> tasks) {
		if(tasks != null){
			String filename = getFilename();
			int size = tasks.size();
			prepareIds(tasks);
			super.write(tasks);
			List<Task> newTasks = new ArrayList<Task>();
			for(Task task: tasks){
				if(!task.getDone())
					newTasks.add(task);
			}
			int newSize = newTasks.size();
			
			tasks.clear();
			tasks.addAll(newTasks);
			newTasks = null;
			
			Logger.addMessage("INFO: wrote " + size + " items to " + filename + "   --- Purged " + (size-newSize) +" done tasks");
		}
	}

}
